<script setup>
import * as echarts from 'echarts';
import {onMounted, ref} from "vue";
import * as myChart from "echarts";
import emitter from "@/utils/buts";
import {useBlackSotre} from "@/stores/black";
import {geEnNum, getApprovalInfo, getType} from "@/api/charts.js";
import * as XLSX from "xlsx";
const isBlack = useBlackSotre()
import { saveAs } from 'file-saver';
const isDownload = ref(false);
const yColumns1 = ref([])
const xColumns1 = ref([])
const yColumns2 = ref([])
const xColumns2 = ref([])
const columns3 = ref([])
const DataNum1 = ref([])
const DataNum2 = ref([])
const DataNum3 = ref([])
const query = ref()
const month = ref()
let indexes = ["人事","财务","行政"]
let myChart1 = null
let myChart2 = null
let myChart3 = null
const columns1 = ref([])
const columns2 = ref([])
const exportToExcel = (name,wsData) => {
  // 创建工作簿
  const wb = XLSX.utils.book_new();
  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(wsData);
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, name);
  // 生成文件 buffer
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
  // 创建 Blob 并触发下载
  const blob = new Blob([wbout], { type: 'application/octet-stream' });
  saveAs(blob, name+`企业数据_${new Date().toISOString().slice(0,10)}.xlsx`);
};
const switchEnter = async (month) => {
  columns1.value=[]
  columns2.value=[]
  let res = await geEnNum(month)
  if (res.length < month) {
    for (let i = res.length; i < month-1; i++) {
      res[0].month.push(res[0].month[i]+1)
      res[0].number.push(0)
    }
  }
  res.forEach(item => {
    // 检查数据有效性
    if (!item.month || !item.number) return;
    item.number.forEach((item, index) => {
      columns1.value.push(item);
    })
    item.month.forEach((monthValue, index) => {
      // 获取当前日期
      const currentDate = new Date();
      // 计算目标月份（自动处理跨年）
      const targetDate = new Date(
          currentDate.getFullYear(),
          currentDate.getMonth() - monthValue, // 月份基于 0，减去 monthValue
          1 // 日期设为 1 避免月末问题
      );
      // 获取年份和月份（月份转为 1-based）
      const year = targetDate.getFullYear();
      const month = targetDate.getMonth() + 1;
      // 格式化为 YYYY-MM
      let groupId = `${year}-${month.toString().padStart(2, '0')}`;
      // 填充容器
      columns2.value.push(groupId);
    });
  });
}
const getData1 =async () =>{
  let res = await getApprovalInfo(query.value)
  if (res.length < query.value) {
    for (let i = res.length; i < query.value; i++) {
      res[i]  = {num:0,name:"暂无",enterpriseId:"无"};
    }
  }
  res.forEach(item => {
    DataNum1.value.push({企业ID:item.enterpriseId,企业名:item.name,数量:item.num});
  });
  let wsData1 = [
    ["企业ID","企业名", "数量"], // 表头
    ...DataNum1.value.map((item,wsData1) => [item.企业ID,item.企业名, item.数量]) // 数据行
  ];
  exportToExcel("企业发起审批量数据",wsData1)
  DataNum1.value = []
}
const getData2 =async () =>{
  await switchEnter(month.value)
  for (let i= 0;i<columns2.value.length;i++) {
    DataNum2.value.push({日期:columns2.value[i],企业数量:columns1.value[i]});
  }
  let wsData2 =[
    ["日期","企业数量"], // 表头
    ...DataNum2.value.map((item,wsData2) => [item.日期,item.企业数量]) // 数据行
  ];
  exportToExcel("企业注册数据",wsData2)
  DataNum2.value = []
}
const getData3 =async () =>{
  let res = await getType()
  DataNum3.value.push({人事:res[0],财务:res[1],行政:res[2]});
  let wsData3 = [
    indexes, // 表头
    ...DataNum3.value.map((item,wsData3) => [item.人事,item.财务,item.行政]) // 数据行
  ];
  exportToExcel("企业审批项类型统计表",wsData3)
  DataNum3.value =[]
}
const getApprovalInfos = async (query)=>{
  let res = await getApprovalInfo(query)
  if (res.length < query) {
    for (let i = res.length; i < query; i++) {
      res[i]  = {num:0,name:"暂无"};
    }
  }
  res.forEach(item => {
    yColumns1.value.push(item.num)
    xColumns1.value.push(item.name)
  });
  updateChart()
}
const geEnNums = async (month)=>{
  await switchEnter(month)
  xColumns2.value=columns2.value
  yColumns2.value=columns1.value
  updateChart()
}
const closeDia=()=>{
  query.value=ref(null)
  month.value=ref(null)
}
const getTypes = async ()=>{
  let res = await getType()
  res.forEach((item,index) => {
      columns3.value.push({value:item,name:indexes[index]});
    })
  updateChart()
}
// 绘制图表

// 独立图表初始化方法
const initChart = (e) => {
  const chartDom1 = document.getElementById('main1')
  const chartDom2 = document.getElementById('main2')
  const chartDom3 = document.getElementById('main3')
  if (myChart1!==null){
    myChart1.dispose();
    myChart2.dispose();
    myChart3.dispose();
    myChart1=null;
    myChart2=null;
    myChart3=null;
  }
  myChart1 = echarts.init(chartDom1,e);
  myChart2 = echarts.init(chartDom2,e);
  myChart3 = echarts.init(chartDom3,e);
  let option1 = {
    title: {
      text: '企业审批数量前五排名表',
      top: '10px',
      left: '26px',
      style: {
        color: 'red',
        showBackground: true,
        backgroundStyle: {color:'red'}
      },
    },
    tooltip: {
      trigger: 'item'
    },
    toolbox: {
      show: true,
      orient: "vertical",
      left: "140vh",
      top: "27vh",
      borderRadius: 5,
      feature: {
        saveAsImage: { show: true },
      },
    },
    yAxis: {},
    xAxis: {
      type: 'category',
      data: xColumns1.value,
      axisLabel: {
        interval:0,
        rotate:-40,//此行与上一行作用在于使得X轴坐标倾斜，避免X轴坐标较多无法显示
        inside: false,//将图形中的字移到图形外边
        fontSize:8//调整坐标轴字体大小
      },
    },
    dataGroupId: '',
    animationDurationUpdate: 500,
    series: {
      type: 'bar',
      id: 'sales',
      data: yColumns1.value,
      color: 	['#ee6666'],
      universalTransition: {
        enabled: true,
        divideShape: 'clone'
      },
      showBackground: true,
      backgroundStyle: {
        color: '#91cc75'
      }
    }
  };
  let option2 = {
    title: {
      text: '近六个月新增企业表',
      top: '10px',
      left: 'center',
      style: {
        color: 'red',
        showBackground: true,
        backgroundStyle: {color:'red'}
      },
    },
    tooltip: {
      trigger: 'item',
    },
    toolbox: {
      show: true,
      orient: "vertical",
      left: "150vh",
      top: "27vh",
      borderRadius: 5,
      feature: {
        saveAsImage: { show: true },
      },
    },
    xAxis: {
      type: 'category',
      data: xColumns2.value ,
      axisLabel: {
        interval:0,
        rotate:-40,
        inside: false,//将图形中的字移到图形外边
        fontSize:10,
        formatter: function (value) {
          return value ;
        }
      },
    },
    yAxis: {},
    dataGroupId: '',
    animationDurationUpdate: 500,
    series: {
      type: 'line',
      id: 'sales',
      data: yColumns2.value ,
      color:'#2ED1CB',
      universalTransition: {
        enabled: true,
        divideShape: 'clone'
      },
      showBackground: true,
      backgroundStyle: {
        color: 'block'
      }
    }
  };
  let option3 = {
    title: {
      text: '各企业提交审批类型统计',
      left: 'center',
      top: '15px'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      bottom: '2%',
    },
    toolbox: {
      show: true,
      orient: "vertical",
      left: "150vh",
      top: "37vh",
      borderRadius: 5,
      feature: {
        saveAsImage: { show: true },
      },
    },
    series: [
      {
        name: '通过比例',
        type: 'pie',
        radius: '50%',
        data: columns3.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  myChart1.setOption(option1)
  myChart2.setOption(option2)
  myChart3.setOption(option3)
}
const updateChart = () => {
  if (!myChart2) {
    initChart()
  } else {
    // 使用merge模式更新数据
    myChart1.setOption({
      xAxis: { data: xColumns1.value },
      series: { data: yColumns1.value }
    })
    myChart2.setOption({
      xAxis: { data: xColumns2.value },
      series: { data: yColumns2.value }
    })
    myChart3.setOption({
      series: { data: columns3.value }
    })
  }
}
emitter.on("chart", (data) => {
  initChart(data); //需要调用的方法
});
onMounted(async ()=>{
  // 先初始化空图表
  if (isBlack.black===false){
    initChart("light")
  }else {
    initChart("dark")
  }



  // 异步加载数据
  await getApprovalInfos(5)
  await geEnNums(6)
  await getTypes()
})
</script>

<template>

  <div id="chart">
  <p id="main1" style="width: 40vh;height: 45vh;"></p>
  <p id="main2" ></p>
  <p id="main3" ></p>
    <el-button style="margin-left: 130vh;margin-top: 1vh" @click="isDownload = true">点击保存数据到本地</el-button>
  </div>
  <el-dialog
      v-model="isDownload"
      width="400"
      title="下载数据"
      :before-close="closeDia()"
  >
    <el-card class="overview-card" header="保存企业发起审批数据">
      <el-input-number min:min="1" :max="10000" v-model="query" style="width: 240px" placeholder="请输入保存排名数"></el-input-number>
      <el-button @click="getData1" style="margin-left: 2vh">下载</el-button>
    </el-card><br>
    <el-card class="overview-card" header="保存企业注册数据">
      <el-input-number min:min="1" :max="1000" v-model="month" style="width: 240px" placeholder="请输入保存月数"></el-input-number>
      <el-button @click="getData2" style="margin-left: 2vh">下载</el-button>
    </el-card><br>
    <el-card class="overview-card" header="保存企业定义审批类型数据">
      <el-button @click="getData3">下载</el-button>
    </el-card>
  </el-dialog>
</template>

<style scoped lang="scss">
#chart {
  margin-left: 30vh;
  width: 135vh;
  height: 55vh;
  margin-top: 4vh;
  border-radius: 10px;
}
#main1{
  margin-left: 8vh;
  border-radius: 10px;
}
#main2{
  width:  40vh;height:  45vh;margin-top: -47vh;
  margin-left: 56vh;
  border-radius: 10px;
}
#main3{
  width:  42.5vh;height:  45vh;margin-top: -47vh;
  margin-left: 104vh;
  border-radius: 10px;
}
</style>